package com.cyp.blogsystem.service.impl;

import cn.hutool.core.util.StrUtil;
import com.cyp.blogsystem.exception.BusinessException;
import com.cyp.blogsystem.mapper.*;
import com.cyp.blogsystem.model.query.ArticleQuery;
import com.cyp.blogsystem.model.request.CreateArticleRequest;
import com.cyp.blogsystem.model.request.UpdateArticleRequest;
import com.cyp.blogsystem.model.vo.ArticleDetailVO;
import com.cyp.blogsystem.model.vo.ArticleVO;
import com.cyp.blogsystem.pojo.Article;
import com.cyp.blogsystem.pojo.ArticleTag;
import com.cyp.blogsystem.pojo.Like;
import com.cyp.blogsystem.pojo.PageResult;
import com.cyp.blogsystem.service.ArticleService;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import lombok.RequiredArgsConstructor;
import java.util.List;
import java.util.stream.Collectors;

@Service
@RequiredArgsConstructor
public class ArticleServiceImpl implements ArticleService {

  private final ArticleMapper articleMapper;
  private final CommentMapper commentMapper;
  private final ArticleTagMapper articleTagMapper;
  private final LikeMapper likeMapper;

  @Override
  @Transactional
  public Long createArticle(Long userId, CreateArticleRequest request) {
    // 1. 创建文章
    // 1.1 构建文章对象
    Article article = new Article();
    article.setUserId(userId);
    article.setTitle(request.getTitle());
    article.setContent(request.getContent());
    article.setSummary(request.getSummary());
    article.setCategoryId(request.getCategoryId());
    article.setStatus(0); // 默认为草稿状态

    // 1.2 保存文章
    articleMapper.insert(article);

    // 2. 处理标签
    if (request.getTagIds() != null && !request.getTagIds().isEmpty()) {
      // 2.1 遍历标签ID
      for (Long tagId : request.getTagIds()) {
        // 2.2 创建文章-标签关联
        ArticleTag articleTag = new ArticleTag();
        articleTag.setArticleId(article.getId());
        articleTag.setTagId(tagId);
        // 2.3 保存关联关系
        articleTagMapper.insert(articleTag);
      }
    }

    // 3. 返回文章ID
    return article.getId();
  }

  @Override
  public PageResult<ArticleVO> getArticleList(ArticleQuery query) {
    // 查询总数
    long total = articleMapper.selectCount(query);
    if (total == 0) {
      return PageResult.empty();
    }

    // 查询列表
    List<Article> articles = articleMapper.selectList(query);
    List<ArticleVO> voList = articles.stream()
        .map(this::convertToVO)
        .collect(Collectors.toList());

    return PageResult.of(total, voList);
  }

  @Override
  public ArticleDetailVO getArticleDetail(Long id) {
    // 查询文章
    Article article = articleMapper.selectById(id);
    if (article == null) {
      throw new BusinessException("文章不存在");
    }

    // 增加浏览量
    articleMapper.incrementViewCount(id);

    // 转换为VO
    return convertToDetailVO(article);
  }

  @Override
  @Transactional
  public void updateArticle(Long id, UpdateArticleRequest request) {
    Article article = articleMapper.selectById(id);
    if (article == null) {
      throw new BusinessException("文章不存在");
    }

    // 更新文章信息
    if (StrUtil.isNotBlank(request.getTitle())) {
      article.setTitle(request.getTitle());
    }
    if (StrUtil.isNotBlank(request.getContent())) {
      article.setContent(request.getContent());
    }
    if (StrUtil.isNotBlank(request.getSummary())) {
      article.setSummary(request.getSummary());
    }
    if (request.getCategoryId() != null) {
      article.setCategoryId(request.getCategoryId());
    }

    articleMapper.updateById(article);

    // 更新标签
    if (request.getTagIds() != null) {
      // 删除原有标签
      articleTagMapper.deleteByArticleId(id);
      // 添加新标签
      for (Long tagId : request.getTagIds()) {
        ArticleTag articleTag = new ArticleTag();
        articleTag.setArticleId(id);
        articleTag.setTagId(tagId);
        articleTagMapper.insert(articleTag);
      }
    }
  }

  @Override
  @Transactional
  public void deleteArticle(Long id) {
    Article article = articleMapper.selectById(id);
    if (article == null) {
      throw new BusinessException("文章不存在");
    }

    // 删除文章
    articleMapper.deleteById(id);
    // 删除相关标签
    articleTagMapper.deleteByArticleId(id);
    // 删除相关评论
    commentMapper.deleteByArticleId(id);
    // 删除相关点赞
    likeMapper.deleteByArticleId(id);
  }

  @Override
  @Transactional
  public void likeArticle(Long userId, Long articleId) {
    // 检查文章是否存在
    Article article = articleMapper.selectById(articleId);
    if (article == null) {
      throw new BusinessException("文章不存在");
    }

    // 检查是否已点赞
    Like like = likeMapper.selectByUserIdAndArticleId(userId, articleId);
    if (like == null) {
      // 添加点赞
      like = new Like();
      like.setUserId(userId);
      like.setArticleId(articleId);
      likeMapper.insert(like);
      // 更新文章点赞数
      articleMapper.incrementLikeCount(articleId);
    } else {
      // 取消点赞
      likeMapper.deleteById(like.getId());
      // 更新文章点赞数
      articleMapper.decrementLikeCount(articleId);
    }
  }

  private ArticleVO convertToVO(Article article) {
    ArticleVO vo = new ArticleVO();
    BeanUtils.copyProperties(article, vo);
    // 设置其他属性...
    return vo;
  }

  private ArticleDetailVO convertToDetailVO(Article article) {
    ArticleDetailVO vo = new ArticleDetailVO();
    BeanUtils.copyProperties(article, vo);
    // 设置其他属性...
    return vo;
  }
}